package com.xunchi.haichuan.data.action;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.struts2.ServletActionContext;

import com.netai.safedoc.utility.TransactionWrapper;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xunchi.haichuan.audit.service.LogService;
import com.xunchi.haichuan.audit.service.LogServiceImpl;
import com.xunchi.haichuan.configurator.model.SystemConfigs;
import com.xunchi.haichuan.data.model.Data;
import com.xunchi.haichuan.data.service.DataService;
import com.xunchi.haichuan.data.service.DataServiceImpl;
import com.xunchi.haichuan.user.model.User;
import com.xunchi.haichuan.utility.MiscUtil;

/**
 * 作者：kongxb<br>
 * 模块名称：数据管理模块<br>
 * 功能描述：数据导入导出<br>
 * 维护记录：2009.12.7, kongxb 创建该类
 */
public class DataAction extends ActionSupport {

    private static final long serialVersionUID = -148536952910480018L;

    private transient File inFile;

    private transient boolean isSearch = false;
    private transient String province;
    private transient String city;
    private transient int validation;
    private transient Date beginDate;
    private transient Date endDate;
    private transient int count;

    private File outFile;
    private String outFileName;

    private DataService dataService;
    private LogService logService;

    private User currentUser;

    /**
     * Struts2默认执行方法
     */
    public String execute() throws Exception {
        return Action.SUCCESS;
    }

    /**
     * 数据导入
     */
    public String importData() throws Exception {
        currentUser = (User) ActionContext.getContext().getSession().get("currentUser");

        dataService = (DataService) TransactionWrapper.decorate(new DataServiceImpl(), true);
        logService = (LogService) TransactionWrapper.decorate(new LogServiceImpl(), true);

        boolean success = dataService.importFromExcelFile(inFile);

        if (success) {
            return Action.SUCCESS;
        } else {
            this.addFieldError("import", this.getText("Data.import.failed"));
            return Action.INPUT;
        }
    }

    /**
     * 数据导出
     */
    public String exportData() throws Exception {
        currentUser = (User) ActionContext.getContext().getSession().get("currentUser");
        String usrId = currentUser != null ? currentUser.getUsrId() : null;

        dataService = (DataService) TransactionWrapper.decorate(new DataServiceImpl());
        logService = (LogService) TransactionWrapper.decorate(new LogServiceImpl(), true);

        if (currentUser.getPermissions().contains("exportData")) { // 有导出权限
            List<Data> list = new ArrayList<Data>();
            if (isSearch) { // 搜索数据
                if (count == -1) {
                    list = dataService.search(province, city, validation, beginDate, endDate);
                } else {
                    list = dataService.search(province, city, validation, beginDate, endDate, count);
                }
            } else {
                int start = 0, limit = SystemConfigs.recordsPerPage;
                list = dataService.getLatestDatas(start, limit);
            }
            outFile = dataService.exportToExcelFile(list);
            outFileName = outFile.getName();
        }

        return Action.SUCCESS;
    }

    public InputStream getInputStream() throws Exception {
        return FileUtils.openInputStream(outFile);
    }

    /**
     * @return the fileName
     */
    public String getFileName() {
        return outFileName;
    }

    /**
     * 提供转换编码后的供下载用的文件名
     * 
     * @return
     */
    public String getDownloadFileName() {
        return MiscUtil.encodeFileName(outFileName, ServletActionContext.getRequest().getHeader("user-agent"),
                SystemUtils.IS_OS_WINDOWS);
    }

    /**
     * 提供下载的文件大小
     * 
     * @return
     */
    public int getContentLength() {
        return (int) this.outFile.length();
    }

    /**
     * @param inFile
     *            the inFile to set
     */
    public void setInFile(File inFile) {
        this.inFile = inFile;
    }

    /**
     * @param isSearch
     *            the isSearch to set
     */
    public void setIsSearch(boolean isSearch) {
        this.isSearch = isSearch;
    }

    /**
     * @param province
     *            the province to set
     */
    public void setProvince(String province) {
        this.province = province;
    }

    /**
     * @param city
     *            the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }

    public void setValidation(int validation) {
        this.validation = validation;
    }

    /**
     * @param beginDate
     *            the beginDate to set
     */
    public void setBeginDate(Date beginDate) {
        this.beginDate = beginDate;
    }

    /**
     * @param endDate
     *            the endDate to set
     */
    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public void setCount(int count) {
        this.count = count;
    }

}
